package com.ideal.tools.ssh.common;

import com.ideal.tools.db.MysqlDBUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by CC on 2016/7/25.
 * 所有的属性都会放在这个盒子里面
 *
 *
 */
public class PropertyBox {

    private static final String Property_Path="/property.properties";

    private static PropertyBox box= new PropertyBox();

    private static Map<String,Object> vals=new HashMap<String, Object>();


    public static Map<String,String> getAllVals(){
        Map<String,String> allVals= new HashMap<String, String>();
        for (Map.Entry<String,Object> e:vals.entrySet()){
            allVals.put(e.getKey(),e.getValue().toString());
        }
        System.out.println("ProxyBox all vals size:"+allVals.size());
        return allVals;
    }

    //这里后面是需要修改的。因为这里现在只支持了string,后面应该可以传递不同的数据类型
    public static String getVal(String key,String dft){
        Object v = vals.get(key);

        if(v==null )
            return dft;
        if(StringUtils.isBlank(v.toString())&&!StringUtils.isBlank(dft))
            return dft;
        return v.toString();
    }

    public static List<String> getVals(String key,String dft){
        List<String> rs = new ArrayList<String>();

        for(Map.Entry<String,Object> entry:vals.entrySet()){
            if(entry.getKey().startsWith(key)){
                Object v = entry.getValue();
                if(v==null || (StringUtils.isBlank(v.toString())&&!StringUtils.isBlank(dft)))
                    v = dft;

                rs.add(v.toString());
            }
        }
        return rs;
    }

    static{
        initProteryFromFile();
        initPropertyFromMysql();
    }

    private static void initPropertyFromMysql(){
        //从数据库中取配置
        Map<String,String> dbPro= null;
        dbPro = MysqlDBUtils.initDBProperty();


        for (String key:PropertyDictory.getKeys()){
            if( dbPro!=null && dbPro.get(key)!=null)
                vals.put(key, dbPro.get(key));
        }

    }

    private static PropertyBox initProteryFromFile(){
        Properties properties = new Properties();
        InputStream in=box.getClass().getResourceAsStream(PropertyBox.Property_Path);
        try {
            properties.load(in);
            for (String key:PropertyDictory.getKeys()){
                vals.put(key, properties.getProperty(key,""));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return box;
    }

    /**
     * 载入数据库中的配置参数
     */
    public static void reflush(){
        initPropertyFromMysql();
    }



}
